<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/7/28
 * Time: 19:16
 */

namespace app\modules\api\models;

use app\models\Goods;
use app\models\Level;
use app\models\MiaoshaGoods;
use app\models\MsGoods;
use app\models\MsOrder;
use app\models\Order;
use app\models\OrderDetail;
use app\models\OrderRefund;
use app\models\Setting;
use app\models\Shop;
use app\models\Store;
use app\models\Coupon;
use app\models\UserCoupon;
use app\models\User;

class OrderDetailForm extends ApiModel
{
    public $store_id;
    public $user_id;
    public $order_id;
    public $order_no;

    public function rules()
    {
        return [
            [['order_id'], 'required'],
        ];
    }

    public function search()
    {
        if (!$this->validate()) {
            return $this->errorResponse;
        }
        $order = Order::findOne([
            'store_id'   => $this->store_id,
            'user_id'    => $this->user_id,
            'id'         => $this->order_id,
            'is_delete'  => 0,
            'is_recycle' => 0,
        ]);
        if (!$order) {
            return [
                'code' => 1,
                'msg'  => '订单不存在',
            ];
        }
        $status = "";
        if ($order->is_pay == 0) {
            $status = '订单未付款';
        } elseif ($order->is_pay == 1 && $order->is_send == 0) {
            $status = '订单待发货';
        } elseif ($order->is_send == 1 && $order->is_confirm == 0) {
            $status = '订单已发货';
        } elseif ($order->is_confirm == 1) {
            $status = '订单已完成';
        }

        $goods_list = OrderDetail::find()->alias('od')
            ->where(['od.order_id' => $order->id, 'od.is_delete' => 0])->all();
        $num        = 0;
        foreach ($goods_list as $i => $item) {
            $newItem                    = [];
            $newItem['goods_id']        = $item['goods_id'];
            $newItem['order_detail_id'] = $item['id'];
            $newItem['name']            = $item->goods->name;
            $newItem['total_price']     = $item['total_price'];
            $newItem['num']             = $item['num'];
            $newItem['attr']            = json_decode($item['attr']);
            $num                        += intval($item['num']);
            $newItem['goods_pic']       = $item['pic'] ?: Goods::getGoodsPicStatic($item['id'])->pic_url;
            $order_refund               = OrderRefund::findOne([
                'order_detail_id' => $item['id'],
                'is_delete'       => 0,
            ]);
            if ($order_refund) {
                $newItem['is_order_refund'] = 1;
            } else {
                $newItem['is_order_refund'] = 0;
            }
            if ($order->is_pay == 1 && $order->is_send == 1) {
                $newItem['order_refund_enable'] = 1;
            } else {
                $newItem['order_refund_enable'] = 0;
            }
            if ($order->is_confirm == 1) {
                $store = Store::findOne($this->store_id);
                if ((time() - $order->confirm_time) > $store->after_sale_time * 86400) {//超过可售后时间
                    $newItem['order_refund_enable'] = 0;
                }
            }
            if ($item['is_level'] == 1 && ($order->discount && $order->discount < 10)) {
                $newItem['is_level'] = 1;
            }
            $newList[] = $newItem;
        }
        if ($order->shop_id) {
            $shop = Shop::find()->select(['name', 'mobile', 'address', 'longitude', 'latitude'])->where(['store_id' => $this->store_id, 'id' => $order->shop_id])->asArray()->one();
        }
        if ($order->before_update_price) {
            if ($order->before_update_price < $order->pay_price) {
                $before_update = "加价";
                $money         = $order->pay_price - $order->before_update_price;
            } else {
                $before_update = "优惠";
                $money         = $order->before_update_price - $order->pay_price;
            }
        } else {
            $before_update = "";
            $money         = "";
        }

        if (!$order->integral) {
            $order->integral = 0;
        }
        return [
            'code' => 0,
            'msg'  => 'success',
            'data' => [
                'order_id'          => $order->id,
                'is_pay'            => $order->is_pay,
                'is_send'           => $order->is_send,
                'is_confirm'        => $order->is_confirm,
                'status'            => $status,
                'express'           => $order->express,
                'express_no'        => $order->express_no,
                'name'              => $order->name,
                'mobile'            => $order->mobile,
                'address'           => $order->address,
                'order_no'          => $order->order_no,
                'addtime'           => date('Y-m-d H:i', $order->addtime),
                'total_price'       => doubleval(sprintf('%.2f', $order->total_price)),
                'express_price'     => doubleval(sprintf('%.2f', $order->express_price)),
                'goods_total_price' => doubleval(sprintf('%.2f', doubleval($order->total_price) - doubleval($order->express_price))),
                'coupon_sub_price'  => $order->coupon_sub_price,
                'pay_price'         => $order->pay_price,
                'num'               => $num,
                'goods_list'        => $newList,
                'is_offline'        => $order->is_offline,
                'content'           => $order->content ? $order->content : "",
                'before_update'     => $before_update,
                'money'             => $money,
                'shop'              => $shop,
                'discount'          => $order->discount,
                'user_coupon_id'    => $order->user_coupon_id,
                'words'             => $order->words,
                'pay_type'          => $order->pay_type,
                'integral'          => \Yii::$app->serializer->decode($order->integral),
                'apply_delete'      => $order->apply_delete
            ],
        ];
    }

    public function searchOpen()
    {
        if (empty($this->order_no)) {
            return [
                'code' => 1,
                'msg'  => '订单号不能为空',
                'data' => []
            ];
        }
        $order = Order::findOne([
            'store_id'   => $this->store_id,
            'order_no'   => $this->order_no,
            'is_recycle' => 0,
        ]);
        if (!$order) {
            return [
                'code' => 1,
                'msg'  => '订单不存在',
                'data' => []
            ];
        }
        $status = "";
        if ($order->is_pay == 0) {
            $status = '订单未付款';
        } elseif ($order->is_pay == 1 && $order->is_send == 0) {
            $status = '订单待发货';
        } elseif ($order->is_send == 1 && $order->is_confirm == 0) {
            $status = '订单已发货';
        } elseif ($order->is_confirm == 1) {
            $status = '订单已完成';
        }

        $order_status = $this->getOrderStatusNumber($order);
        $status = getOrderStatustxt($order_status);
        $goods_list = OrderDetail::find()->alias('od')
            ->where(['od.order_id' => $order->id, 'od.is_delete' => 0])->all();
        $num        = 0;
        foreach ($goods_list as $i => $item) {
            $newItem                    = [];
            $newItem['goods_id']        = $item['goods_id'];
            $newItem['order_detail_id'] = $item['id'];
            $newItem['name']            = $item->goods->name;
            $newItem['total_price']     = $item['total_price'];
            $newItem['num']             = $item['num'];
            $newItem['attr']            = json_decode($item['attr']);
            $num                        += intval($item['num']);
            $newItem['goods_pic']       = $item['pic'] ?: Goods::getGoodsPicStatic($item['id'])->pic_url;
            $order_refund               = OrderRefund::findOne([
                'order_detail_id' => $item['id'],
                'is_delete'       => 0,
            ]);
            if ($order_refund) {
                $newItem['is_order_refund'] = 1;
            } else {
                $newItem['is_order_refund'] = 0;
            }
            if ($order->is_pay == 1 && $order->is_send == 1) {
                $newItem['order_refund_enable'] = 1;
            } else {
                $newItem['order_refund_enable'] = 0;
            }
            if ($order->is_confirm == 1) {
                $store = Store::findOne($this->store_id);
                if ((time() - $order->confirm_time) > $store->after_sale_time * 86400) {//超过可售后时间
                    $newItem['order_refund_enable'] = 0;
                }
            }
            if ($item['is_level'] == 1 && ($order->discount && $order->discount < 10)) {
                $newItem['is_level'] = 1;
            }
            $newList[] = $newItem;
        }
        if ($order->shop_id) {
            $shop = Shop::find()->select(['name', 'mobile', 'address', 'longitude', 'latitude'])->where(['store_id' => $this->store_id, 'id' => $order->shop_id])->asArray()->one();
        }
        if ($order->before_update_price) {
            if ($order->before_update_price < $order->pay_price) {
                $before_update = "加价";
                $money         = $order->pay_price - $order->before_update_price;
            } else {
                $before_update = "优惠";
                $money         = $order->before_update_price - $order->pay_price;
            }
        } else {
            $before_update = "";
            $money         = "";
        }

        if (!$order->integral) {
            $order->integral = 0;
        }
        $address_data = \Yii::$app->serializer->decode($order->address_data);

        return [
            'code' => 0,
            'msg'  => 'success',
            'data' => [
                'order_id'          => $order->id,
                'is_pay'            => $order->is_pay,
                'is_send'           => $order->is_send,
                'is_confirm'        => $order->is_confirm,
                'status'            => $status,
                'order_status'      => $order_status,
                'shop_name'         => $this->store->name,
                'express'           => $order->express,
                'express_no'        => $order->express_no,
                'name'              => $order->name,
                'mobile'            => $order->mobile,
                'province'          => $address_data->province,
                'city'              => $address_data->city,
                'area'              => $address_data->district,
                'detail'            => $address_data->detail,
                'address'           => $order->address,
                'order_no'          => $order->order_no,
                'addtime'           => date('Y-m-d H:i:s', $order->addtime),
                'total_price'       => doubleval(sprintf('%.2f', $order->total_price)),
                'express_price'     => doubleval(sprintf('%.2f', $order->express_price)),
                'goods_total_price' => doubleval(sprintf('%.2f', doubleval($order->total_price) - doubleval($order->express_price))),
                'coupon_sub_price'  => $order->coupon_sub_price,
                'user_coupon_id'    => $order->user_coupon_id,
                'conpon_info'       => $this->getConponInfo($order->user_coupon_id),
                'pay_price'         => $order->pay_price,
                'num'               => $num,
                'goods_list'        => $newList,
                'is_offline'        => $order->is_offline,
                'content'           => $order->content ? $order->content : "",
                'before_update'     => $before_update,
                'money'             => $money,
                'shop'              => $shop,
                'user_nickname'     => User::findOne($order->user_id)->nickname,
                'discount'          => $order->discount,
                'words'             => $order->words,
                'pay_type'          => $order->pay_type,
                'integral'          => \Yii::$app->serializer->decode($order->integral),
                'apply_delete'      => $order->apply_delete,
                'refund_info' => OrderRefund::find()->where(['order_id'=> $order->id])->select([
                    'order_refund_no', // 退款单号
                    'type',         // 售后类型：1=退货退款，2=换货
                    'refund_price', // 退款金额
                    'desc',         // 退款说明
                    'pic_list',     // 凭证图片  json
                    'status',       // 状态：0=待商家处理，1=同意并已退款，2=已同意换货，3=已拒绝退换货
                    'refuse_desc',  // 拒绝原因
                    'from_unixtime(addtime) as addtime', // 创建时间
                    'response_time' // 商家响应时间
                ])->asArray()->one()
            ],
        ];
    }

    /**
     * 获取订单状态数
     * @param $order
     * @return bool|int
     * author eRic
     * dateTime 2019-08-28 11:25
     */
    public function getOrderStatusNumber($order)
    {
        if (!is_object($order)) {
            return false;
        }
        $one = OrderRefund::find()->where(['order_id' => $order->id,'type' => 1])->select(['order_id'])->one();
        if($one){
            if($one->status == 0){
                return 6; // 待处理
            }else{
                return 4; // 已退款
            }
        }
        $is_pay       = $order->is_pay;
        $is_send      = $order->is_send;
        $is_confirm   = $order->is_confirm;
        $is_delete    = $order->is_delete;
        $is_cancel    = $order->is_cancel;
        $apply_delete = $order->apply_delete;

        if (!$is_pay ) {
            if($is_delete || $is_cancel){
                return 5; // 已取消
            }else{
                return 0; // 未付款
            }
        } else {
            if($is_delete){
                return 5; // 已取消
            }
            if($apply_delete){
                return 6; // 待处理
            }
            if (!$is_send) {
                return 1; // 待发货
            }
            if ($is_confirm) {
                return 3; // 已完成
            }
            return 2;   //待收货
        }
    }

    /**
     * 获取优惠券信息
     * @param $user_coupon_id 用户使用优惠券ID
     * @return array|null|\yii\db\ActiveRecord
     * author eRic
     * dateTime 2019-08-27 16:15
     */
    public function getConponInfo($user_coupon_id)
    {
        $info = UserCoupon::find()->alias('uc')->where([
            'uc.is_delete' => 0,
            'uc.id'        => $user_coupon_id,
        ])->leftJoin(Coupon::tableName() . 'c', 'c.id=uc.coupon_id')
            ->select(['c.name', 'c.min_price', 'c.sub_price'])
            ->asArray()->one();
        return $info;
    }

    public function clerk()
    {
        if (stripos($this->order_no, 'M') > -1) {
            $order = MsOrder::find()->where([
                'store_id' => $this->store_id, 'order_no' => $this->order_no, 'is_delete' => 0
            ])->one();
            if (!$order) {
                return [
                    'code' => 1,
                    'msg'  => '订单不存在-1',
                ];
            }
            $goods                     = MsGoods::find()->where(['id' => $order->goods_id])->one();
            $newList[0]['attr']        = json_decode($order->attr, true);
            $newList[0]['goods_pic']   = $order->pic;
            $newList[0]['num']         = $order->num;
            $newList[0]['id']          = $goods->id;
            $newList[0]['name']        = $goods->name;
            $newList[0]['total_price'] = $order->total_price;

            $num = $order->num;
        } else {
            $order = Order::findOne([
                'store_id'  => $this->store_id,
                'order_no'  => $this->order_no,
                'is_delete' => 0,
            ]);
            if (!$order) {
                return [
                    'code' => 1,
                    'msg'  => '订单不存在',
                ];
            }

            $goods_list = OrderDetail::find()->alias('od')
                ->where(['od.order_id' => $order->id, 'od.is_delete' => 0])->all();
            $num        = 0;
            $newList    = [];
            foreach ($goods_list as $i => $item) {
                $newItem                    = [];
                $newItem['goods_id']        = $item['goods_id'];
                $newItem['order_detail_id'] = $item['id'];
                $newItem['name']            = $item->goods->name;
                $newItem['total_price']     = $item['total_price'];
                $newItem['num']             = $item['num'];
                $newItem['attr']            = json_decode($item['attr']);
                $num                        += intval($item['num']);
                $newItem['goods_pic']       = Goods::getGoodsPicStatic($item['goods_id'])->pic_url;
                $order_refund               = OrderRefund::findOne([
                    'order_detail_id' => $item['id'],
                    'is_delete'       => 0,
                ]);
                if ($order_refund) {
                    $newItem['is_order_refund'] = 1;
                } else {
                    $newItem['is_order_refund'] = 0;
                }
                if ($order->is_pay == 1 && $order->is_send == 1) {
                    $newItem['order_refund_enable'] = 1;
                } else {
                    $newItem['order_refund_enable'] = 0;
                }
                if ($order->is_confirm == 1) {
                    $store = Store::findOne($this->store_id);
                    if ((time() - $order->confirm_time) > $store->after_sale_time * 86400) {//超过可售后时间
                        $newItem['order_refund_enable'] = 0;
                    }
                }
                $newList[] = $newItem;
            }
        }
        $status = "";
        if ($order->is_pay == 0) {
            $status = '订单未付款';
        } elseif ($order->is_pay == 1 && $order->is_send == 0) {
            $status = '订单待发货';
        } elseif ($order->is_send == 1 && $order->is_confirm == 0) {
            $status = '订单已发货';
        } elseif ($order->is_confirm == 1) {
            $status = '订单已完成';
        }

        return [
            'code' => 0,
            'msg'  => 'success',
            'data' => [
                'order_id'          => $order->id,
                'is_pay'            => $order->is_pay,
                'is_send'           => $order->is_send,
                'is_confirm'        => $order->is_confirm,
                'status'            => $status,
                'express'           => $order->express,
                'express_no'        => $order->express_no,
                'name'              => $order->name,
                'mobile'            => $order->mobile,
                'address'           => $order->address,
                'order_no'          => $order->order_no,
                'addtime'           => date('Y-m-d H:i', $order->addtime),
                'total_price'       => doubleval(sprintf('%.2f', $order->total_price)),
                'express_price'     => doubleval(sprintf('%.2f', $order->express_price)),
                'goods_total_price' => doubleval(sprintf('%.2f', doubleval($order->total_price) - doubleval($order->express_price))),
                'coupon_sub_price'  => $order->coupon_sub_price,
                'pay_price'         => $order->pay_price,
                'num'               => $num,
                'goods_list'        => $newList,
                'is_offline'        => $order->is_offline,
                'content'           => $order->content ? $order->content : ""
            ],
        ];
    }
}
